package com.wyg.blog.controller.view_blog;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyg.blog.model.blog.Blog;
import com.wyg.blog.model.blog.Comment;
import com.wyg.blog.model.blog.MyComment;
import com.wyg.blog.service.blog.BlogService;
import com.wyg.blog.service.blog.CommentService;
import com.wyg.blog.service.blog.TagService;
import com.wyg.blog.service.blog.TypeService;
import com.wyg.blog.utils.ApiLimit;
import com.wyg.blog.utils.IpAddress;
import com.wyg.blog.utils.JsonResult;
import com.wyg.blog.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: WYG
 * @time: 2020/7/7 21:53
 */
@RestController
@RequestMapping("/api/view/blog")
public class ViewBlogController {

    private static Logger logger = LoggerFactory.getLogger(ViewBlogController.class);

    @Autowired
    BlogService blogService;

    @Autowired
    TypeService typeService;

    @Autowired
    TagService tagService;

    @Autowired
    CommentService commentService;

    @Autowired
    private RedisUtil redisUtil;


    @GetMapping("/getAllBlogs")
    @CrossOrigin
    public JsonResult<List<Map<String,Object>>> getAllBlogs(@RequestParam("current") Integer current, @RequestParam("size") Integer size){
        Page<Blog> page = new Page<>(current, size);
        IPage<Blog> blogIPage = blogService.selectAllBlogs(page);
        List<Map<String,Object>> results = new ArrayList<>();
        List<Blog> blogs = blogIPage.getRecords();
        Integer Current = (int) blogIPage.getCurrent();
        Integer Size = (int) blogIPage.getSize();
        Integer Total = (int) blogIPage.getTotal();
        for(int i = 0; i < blogs.size(); i++){
            Map<String,Object> result = new HashMap<>();
            Blog blog = blogs.get(i);
            String TypeName = typeService.selectTypeName(blog.getType_id());
            List<String> tagNames = tagService.selectTagNameByBid(blog.getId());
            result.put("id", blog.getId().toString());
            result.put("title", blog.getTitle());
            result.put("create_time", blog.getCreate_time());
            result.put("description", blog.getDescription());
            result.put("views", blog.getViews().toString());
            result.put("likes", blog.getLikes().toString());
            result.put("first_picture", blog.getFirst_picture());
            result.put("type", TypeName);
            result.put("tags", tagNames.toString());
            result.put("current", Current.toString());
            result.put("size", Size.toString());
            result.put("total",Total.toString());
            results.add(result);
        }
        return new JsonResult<>(results,"200","全部博客查询成功!");
    }

    @GetMapping("/getLatestBlog")
    @CrossOrigin
    public JsonResult<List<Map<String,Object>>> getLatestBlog(){
        List<Blog> blogs = blogService.selectLatestBlog();
        List<Map<String,Object>> results = new ArrayList<>();
        for(int i = 0; i < blogs.size(); i++) {
            Blog blog = blogs.get(i);
            Map<String,Object> result = new HashMap<>();
            result.put("id", blog.getId().toString());
            result.put("title", blog.getTitle());
            result.put("create_time", blog.getCreate_time());
            String typeName = typeService.selectTypeName(blog.getType_id());
            result.put("type", typeName);
            result.put("type_id", blog.getType_id().toString());
            results.add(result);
        }
        return new JsonResult<>(results,"200","最新博客查询成功!");
    }

    @GetMapping("/getBlogsByTypeId")
    @CrossOrigin
    public JsonResult<IPage<Blog>> getBlogsByTypeId(@RequestParam("current") Integer current, @RequestParam("size") Integer size,
                                                    @RequestParam("type_id") Integer type_id){
        Page<Blog> page = new Page<>(current, size);
        IPage<Blog> blogIPage = blogService.selectBlogByTypeId(page, type_id);
        if(!blogIPage.getRecords().isEmpty()){
            return new JsonResult<>(blogIPage, "200", "分类查询博客成功!");
        }else {
            return new JsonResult<>(null, "704", "该分类下暂无博客!");
        }
    }

    @GetMapping("/getBlogsByTagId")
    @CrossOrigin
    public JsonResult<List<Map<String,Object>>> getBlogsByTagId(@RequestParam("current") Integer current, @RequestParam("size") Integer size,
                                                    @RequestParam("tag_id") Integer tag_id){
        Page<Blog> page = new Page<>(current, size);
        IPage<Blog> blogIPage = blogService.selectBlogByTagId(page, tag_id);
        if(!blogIPage.getRecords().isEmpty()) {
            List<Blog> blogs = blogIPage.getRecords();
            Integer Current = (int)blogIPage.getCurrent();
            Integer Size = (int)blogIPage.getSize();
            Integer total = (int)blogIPage.getTotal();
            List<Map<String,Object>> results = new ArrayList<>();
            for(int i = 0; i < blogs.size(); i++){
                Blog blog = blogs.get(i);
                Map<String,Object> result = new HashMap<>();
                List<String> tagNames =  tagService.selectTagNameByBid(blog.getId());
                String typeName = typeService.selectTypeName(blog.getType_id());
                result.put("id", blog.getId().toString());
                result.put("title", blog.getTitle());
                result.put("create_time", blog.getCreate_time());
                result.put("typeName", typeName);
                result.put("tagNames", tagNames.toString());
                result.put("description", blog.getDescription());
                result.put("first_picture", blog.getFirst_picture());
                result.put("likes", blog.getLikes().toString());
                result.put("views", blog.getViews().toString());
                result.put("current", Current.toString());
                result.put("size", Size.toString());
                result.put("total", total.toString());
                results.add(result);
            }
            return new JsonResult<>(results, "200", "标签查询博客成功!");
        } else {
            return new JsonResult<>(null, "705", "该标签下暂无博客");
        }
    }

    @GetMapping("/getArchiveBlog")
    @CrossOrigin
    public JsonResult<List<Map<String,Object>>> getArchiveBlog(@RequestParam("current") Integer current,
                                                               @RequestParam("size") Integer size){
        Page<Map> page = new Page<>(current, size);
        IPage<Map<String, String>> blogIPage = blogService.selectBlogInfo(page);
        List<Map<String, String>> blogs = blogIPage.getRecords();
        List<Map<String,Object>> results = new ArrayList<>();
        Integer Current = (int) blogIPage.getCurrent();
        Integer Size = (int) blogIPage.getSize();
        Integer Total = (int) blogIPage.getTotal();
        for(int i = 0; i < blogs.size(); i++){
            Map<String,Object> result = new HashMap<>();
            result.putAll(blogs.get(i));
            result.put("current", "" + Current);
            result.put("size", "" + Size);
            result.put("total", "" + Total);
            results.add(result);
        }
        return new JsonResult<>(results, "200", "归档博客查询成功!");
    }

    @GetMapping("/getBlogById")
    @CrossOrigin
    public JsonResult<Map<String, Object>> getBlogById(Integer id){
        Blog blog = blogService.selectBlogById(id);
        List<String> tagNames = tagService.selectTagNameByBid(id);
        Integer commentNumber = commentService.selectCommentCountByBid(id);
        List<MyComment<Comment>> myComments = commentService.selectCommentsByBid(id);
        String typeName = typeService.selectTypeName(blog.getType_id());
        Map<String, Object> results = new HashMap<>();
        results.put("blog", blog);
        results.put("tagNames", tagNames);
        results.put("commentNumber", commentNumber);
        results.put("comments", myComments);
        results.put("typeName", typeName);
        return new JsonResult<>(results, "200", "博客查询成功!");
    }

    @GetMapping("/updateViews")
    @CrossOrigin
    public JsonResult<Integer> updateViews(@RequestParam("id") Integer id, @RequestParam("ipAddress") String ipAddress){
        logger.info("访问ip地址为:" + ipAddress);
        String key = "view_ip:" + id + ":" + ipAddress;
        boolean visited = redisUtil.hasKey(key);
        if (!visited) {
            redisUtil.set(key, 1, 2 * 24 * 60);
            boolean res = blogService.renewViews(id);
            if(res){
                return new JsonResult<>(1,"200","更新成功!");
            }else {
                return new JsonResult<>(0,"706","更新失败!");
            }
        } else {
            return new JsonResult<>(0,"707","两天之内阅读过该文章!");
        }
    }

    @GetMapping("/updateLikes")
    @CrossOrigin
    public JsonResult<Integer> updateLikes(@RequestParam("id") Integer id, @RequestParam("ipAddress") String ipAddress){
        logger.info("访问ip地址为:" + ipAddress);
        String key = "like_ip:" + id + ":" + ipAddress;
        boolean visited = redisUtil.hasKey(key);
        if (!visited) {
            redisUtil.set(key, 1, 2 * 24 * 60);
            boolean res = blogService.renewLikes(id);
            if(res){
                return new JsonResult<>(1,"200","点赞成功!");
            }else {
                return new JsonResult<>(0,"706","点赞失败!");
            }
        } else {
            return new JsonResult<>(0,"707","点赞失败，您已点赞过该文章!");
        }
    }

}
